package com.guigu.qingcheng.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.qingcheng.excption.GuliException;
import com.guigu.qingcheng.mapper.*;
import com.guigu.qingcheng.pojo.*;
import com.guigu.qingcheng.pojo.vo.Goods;
import com.guigu.qingcheng.pojo.vo.SpuAndSku;
import com.guigu.qingcheng.service.AuditSpuInfoService;
import com.guigu.qingcheng.service.TbSpuService;
import com.guigu.qingcheng.utils.IdWorker;
import com.guigu.qingcheng.utils.PageUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;


/**
*
* @author Jiang
* @date 2020/07/25
*/
@Service
public class TbSpuServiceImpl implements TbSpuService {
    @Autowired(required = false)
    private TbSpuMapper tbSpuMapper;

    @Autowired(required = false)
    private IdWorker idWorker;

    @Autowired(required = false)
    private TbSkuMapper tbSkuMapper;

    @Autowired(required = false)
    private TbCategoryMapper tbCategoryMapper;

    @Autowired(required = false)
    private TbCategoryBrandMapper tbCategoryBrandMapper;

    @Autowired
    private AuditSpuInfoService auditSpuInfoService;

    @Autowired
    private AmqpTemplate amqpTemplate;



    @Override
    public List<TbSpu> queryAll() {
        List<TbSpu> tbSpu = tbSpuMapper.selectAll();
            return tbSpu;
    }

    @Override
    public PageUtil<TbSpu> findListAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        Page<TbSpu> pages = (Page<TbSpu>) tbSpuMapper.selectAll();
        PageUtil<TbSpu> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
    }


    @Override
    public PageUtil<TbSpu> pageQueryByAll(Integer pageNum, Integer pageSize, TbSpu tbSpu) {
        Example example=new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        // 判断商品是不被逻辑删除的
        criteria.andEqualTo("isDelete","0");
        // 通过商品名称查询商品
        if(!StringUtils.isEmpty(tbSpu.getName())){
            criteria.andLike("name","%"+tbSpu.getName()+"%");
        }
        // 通过商品品牌查询商品
        if(!StringUtils.isEmpty(tbSpu.getBrandId())){
           criteria.andEqualTo("brandId",tbSpu.getBrandId());
        }
        // 通过商品三级分类查询商品
        if(!StringUtils.isEmpty(tbSpu.getCategory3Id())){
            criteria.andEqualTo("category3Id",tbSpu.getCategory3Id());
        }
        PageHelper.startPage(pageNum,pageSize);
        Page<TbSpu> pages = (Page<TbSpu>) tbSpuMapper.selectByExample(example);
        PageUtil<TbSpu> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
     }


    @Override
    public boolean saveTbSpu(TbSpu tbSpu) {
        int insert = tbSpuMapper.insert(tbSpu);
        if(insert>0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateTbSpu(TbSpu tbSpu) {
        int i = tbSpuMapper.updateByPrimaryKeySelective(tbSpu);
        if(i>0){
            return true;
        }
        return false;
    }


    @Override
    public boolean deleteById(String id) {
        TbSpu spu = tbSpuMapper.selectByPrimaryKey(id);
        int i = 0;
        if (spu.getIsDelete().equals("1")){
            i = tbSpuMapper.deleteByPrimaryKey(id);
        }
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public TbSpu findById(String id) {
        TbSpu tbSpu = tbSpuMapper.selectByPrimaryKey(id);
        return tbSpu;
    }

    @Override
    public boolean saveGoods(Goods goods) {
        int result = 0;

        //保存一个spu的信息
        TbSpu spu = goods.getSpu();
        if (StringUtils.isEmpty(spu.getId())){
            spu.setId(idWorker.nextId()+"");
            result = tbSpuMapper.insert(spu);
        }else {
            // 删除原有的sku列表
            Example example = new Example(TbSku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId",spu.getId());

            tbSkuMapper.deleteByExample(criteria);

            // 执行spu修改
            tbSpuMapper.updateByPrimaryKeySelective(spu);
        }

        //保存sku列表的信息
        Date date=new Date();
        //分类对象
        TbCategory category = tbCategoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        List<TbSku> skuList = goods.getSkuList();
        for (TbSku sku:skuList){

            if (StringUtils.isEmpty(sku.getId())){//新增
                sku.setId(idWorker.nextId()+"");
                sku.setCreateTime(date);//创建日期
            }
            sku.setSpuId(spu.getId());
            //sku名称  =spu名称+规格值列表
            String name = spu.getName();
            // 不启用spec列表
            if (StringUtils.isEmpty(sku.getSpec()))
                sku.setSpec("{}");
            //sku.getSpec()  {"颜色":"红","机身内存":"64G"}
            Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            for (String value:specMap.values()){
                name+=" "+value;
            }
            sku.setName(name);//名称
            sku.setUpdateTime(date);//修改日期
            sku.setCategoryId(spu.getCategory3Id());//分类id
            sku.setCategoryName(category.getName());//分类名称
            sku.setCommentNum(0);//评论数
            sku.setSaleNum(0);//销售数量
            tbSkuMapper.insert(sku);
            result = result + 1;
        }
        //创建分类和品牌联系
        TbCategoryBrand categoryBrand = new TbCategoryBrand();
        categoryBrand.setBrandId(spu.getBrandId());
        categoryBrand.setCategoryId(spu.getCategory3Id());
        int count = tbCategoryBrandMapper.selectCount(categoryBrand);
        if (count==0){
            tbCategoryBrandMapper.insert(categoryBrand);
            result = result + 1;
        }
        if (result>1)
            return true;
        return false;
    }

    @Override
    public boolean isDeleteById(String id) {
        TbSku tbSku = tbSkuMapper.selectByPrimaryKey(id);
        TbSpu spu = new TbSpu();
        spu.setId(tbSku.getSpuId());
        spu.setIsDelete("1");
        int i = this.tbSpuMapper.updateByPrimaryKeySelective(spu);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public void audit(String id, String status, String message) {
        TbSku tbSku = tbSkuMapper.selectByPrimaryKey(id);
        // 通过商品Id修改商品状态是否通过审核
        TbSpu spu = new TbSpu();
        spu.setId(tbSku.getSpuId());
        spu.setStatus(status);
        // 判断商品是否通过审核  通过则自动上架
        if ("1".equals(status)){
            // 自动上架
            spu.setIsMarketable("1");
            //根据spuId查询sku并且将查询结果返回给上架交换器
            Example example = new Example(TbSku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId",id);
            List<TbSku> tbSkus = tbSkuMapper.selectByExample(example);
            amqpTemplate.convertAndSend("exchange.onGoods","", tbSkus);
        }else { // 不通过则放入回收站
            spu.setIsDelete("1");
        }
        // 修改状态操作
        tbSpuMapper.updateByPrimaryKeySelective(spu);

        // 记录商品审核日志
        AuditSpuInfo auditSpuInfo = new AuditSpuInfo();
        if ("1".equals(status)) {
            // 审核通过
            auditSpuInfo.setAudit("审核通过");
        }else {
            // 审核不通过
            auditSpuInfo.setAudit("审核不通过");
        }
        // TODO 重新获取登录名称
        auditSpuInfo.setAuditName("张三");
        auditSpuInfo.setAuditTime(new Date());
        auditSpuInfo.setSkuId(id);
        // 审核结果
        if (message.equals("") || message == null){
            auditSpuInfo.setMessage("无");
        }else {
            auditSpuInfo.setMessage(message);
        }
        auditSpuInfoService.insertAuditSpuInf(auditSpuInfo);

        // TODO 记录商品日志   需要自行创建数据库表

    }

    @Override
    public void pull(String id) {
        // 将商品下架
        TbSpu spu = new TbSpu();
        spu.setId(id);
        spu.setIsMarketable("0");
        // 修改操作
        tbSpuMapper.updateByPrimaryKeySelective(spu);
        //根据spuId查询sku并且将查询结果返回给下架交换器
        Example example = new Example(TbSku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<TbSku> tbSkus = tbSkuMapper.selectByExample(example);
        amqpTemplate.convertAndSend("exchange.offGoods","", tbSkus);
    }

    @Override
    public void put(String id) {
        // 将商品上架
        // 判断商品是否通过审核
        TbSpu spu = tbSpuMapper.selectByPrimaryKey(id);
        // 判断商品是否通过审核
        if (!"1".equals(spu.getStatus())){
            throw new GuliException(20001, "该商品未通过审核");
        }
        spu.setIsMarketable("1");
        // 修改操作
        tbSpuMapper.updateByPrimaryKeySelective(spu);
        //根据spuId查询sku并且将查询结果返回给上架交换器
        Example example = new Example(TbSku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",id);
        List<TbSku> tbSkus = tbSkuMapper.selectByExample(example);
        amqpTemplate.convertAndSend("exchange.onGoods","", tbSkus);

        // TODO 记录商品日志
    }

    @Override
    public Integer putMany(String[] ids) {
        // 模板对象创建 判断条件
        Example example = new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(ids));// 通过Id去修改
        criteria.andEqualTo("isMarketable","0");// 判断是下架的商品
        criteria.andEqualTo("status","1"); // 判断商品是通过审核的
        criteria.andEqualTo("isDelete","0"); // 判断商品是非删除的
        // 修改的字段
        TbSpu spu = new TbSpu();
        spu.setIsMarketable("1");
        // 修改操作
        int i = tbSpuMapper.updateByExampleSelective(spu, example);
        // 将上架了多少商品数 返回
        return i;
    }


    @Override
    public void recycledGoods(String id) {
        // 通过Id将商品通过某个字段逻辑回收
        TbSpu spu = new TbSpu();
        spu.setId(id);
        spu.setIsDelete("0");
        // 修改操作
        tbSpuMapper.updateByPrimaryKeySelective(spu);
    }

    @Override
    public Goods findGoodsById(String id) {
        // 查询 spu 对象
        TbSpu spu = tbSpuMapper.selectByPrimaryKey(id);

        // 创建查询模板对象
        Example example = new Example(TbSku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", id);
        // 查询 sku 对象列表集合
        List<TbSku> skuList = tbSkuMapper.selectByExample(example);

        // 封装 goods 对象返回
        Goods goods = new Goods();
        // 封装 spu 对象
        goods.setSpu(spu);
        // 封装 sku 对象列表集合
        goods.setSkuList(skuList);

        return goods;
    }

    @Override
    public PageUtil<TbSpu> selectSpuByStatus(Integer pageNum, Integer pageSize, TbSpu tbSpu) {
        Example example = new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();
        // 判断是未审核的商品
        criteria.andEqualTo("status", "0");
        // 判断商品是不被逻辑删除的
        criteria.andEqualTo("isDelete", "0");
        // 通过商品名称查询商品
        if(!StringUtils.isEmpty(tbSpu.getName())){
            criteria.andLike("name","%"+tbSpu.getName()+"%");
        }
        // 通过商品品牌查询商品
        if(!StringUtils.isEmpty(tbSpu.getBrandId())){
            criteria.andEqualTo("brandId",tbSpu.getBrandId());
        }
        // 通过商品三级分类查询商品
        if(!StringUtils.isEmpty(tbSpu.getCategory3Id())){
            criteria.andEqualTo("category3Id",tbSpu.getCategory3Id());
        }

        PageHelper.startPage(pageNum,pageSize);
        Page<TbSpu> pages = (Page<TbSpu>) tbSpuMapper.selectByExample(example);
        PageUtil<TbSpu> pageUtil=new PageUtil<>();
        pageUtil.setRows(pages.getResult());
        pageUtil.setTotal(pages.getTotal());
        return pageUtil;
    }

    @Override
    public PageUtil<SpuAndSku> selectSpuAndSkuIsDelete(Integer pageNum, Integer pageSize, TbSpu tbSpu) {
        PageHelper.startPage(pageNum, pageSize);
        List<SpuAndSku> spuAndSkus = tbSpuMapper.selectSpuAndSkuIsDelete(tbSpu);
        PageInfo<SpuAndSku> info = new PageInfo(spuAndSkus);
        PageUtil<SpuAndSku> pageUtil = new PageUtil(info.getTotal(),info.getList());
        return pageUtil;
    }

    @Override
    public PageUtil<SpuAndSku> selectSpuAndSkuOnStatus(Integer pageNum, Integer pageSize, TbSpu tbSpu) {
        PageHelper.startPage(pageNum, pageSize);
        List<SpuAndSku> spuAndSkus = tbSpuMapper.selectSpuAndSkuOnStatus(tbSpu);
        PageInfo<SpuAndSku> info = new PageInfo(spuAndSkus);
        PageUtil<SpuAndSku> pageUtil = new PageUtil(info.getTotal(),info.getList());
        return pageUtil;
    }

    @Override
    public PageUtil<SpuAndSku> selectSpuAndSkuDelete(Integer pageNum, Integer pageSize, TbSpu tbSpu) {
        PageHelper.startPage(pageNum, pageSize);
        List<SpuAndSku> spuAndSkus = tbSpuMapper.selectSpuAndSkuDelete(tbSpu);
        PageInfo<SpuAndSku> info = new PageInfo(spuAndSkus);
        PageUtil<SpuAndSku> pageUtil = new PageUtil(info.getTotal(),info.getList());
        return pageUtil;
    }
}
